package org.sction.bean.listener;

import java.io.File;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.sction.action.core.ActionUtils;
import org.sction.cache.CacheManager;
import org.sction.manager.SystemHelper;
import org.sction.util.ClassPathScanHandler;


public class BeanListener implements ServletContextListener {
	private static final Logger logger = Logger.getLogger(BeanListener.class);
	private static String scanningPath = ".";

	public static String getScanningPath() {
		return scanningPath;
	}

	public void contextDestroyed(ServletContextEvent arg0) {
		CacheManager.destroyed();
		logger.info("\u7ba1\u7406\u76d1\u542c\u5668\u9500\u6bc1.");
	}

	public void contextInitialized(ServletContextEvent sce) {
		logger.info("\u7ba1\u7406\u76d1\u542c\u5668\u5de5\u4f5c\u542f\u52a8...");
		ServletContext servletContext = sce.getServletContext();
		// AideSNManager.init(new
		// File(servletContext.getRealPath("/")).getParent());
		// String webRootRealPath = servletContext.getRealPath("/");
		scanningPath = servletContext.getInitParameter("ScanningPath");
		System.setProperty("projectpath", new File("").getAbsolutePath());
		System.setProperty("webpath", servletContext.getContextPath());
		System.setProperty("webrealpath", servletContext.getRealPath("/"));
		ActionUtils.path = servletContext.getContextPath();
		ActionUtils.realpath = servletContext.getRealPath("/");
		scanning(scanningPath, servletContext);
		logger.info("\u7ba1\u7406\u76d1\u542c\u5668\u5de5\u4f5c\u5b8c\u6210.");
		logger.info(SystemHelper.getRAMinfox());
	}

	/**
	 * 扫描指定包 将注解的Bean或Action创建并缓存
	 * 
	 * @param scanningPath
	 */
	public static void scanning(String scanningPath,
			ServletContext servletContext) {
		ClassPathScanHandler handler = new ClassPathScanHandler();
		String[] scanningPaths = scanningPath.split(",");
		for (String packagepath : scanningPaths) {
			logger.info("Scanning path :" + packagepath);
			Set<Class<?>> classes = handler.getPackageAllClasses(packagepath,
					true);
			for (Class<?> clazz : classes) {
				CacheManager.putAction(clazz);
			}
		}
	}

}
